<?php

namespace App\V3\V3_2_7\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use App\Helper\Utils\TimeUtil;
use App\V3\V3_2_7\Services\QuotationNoService;
use App\V3\V3_2_7\Models\QuotationNoModel;
use App\V3\V3_2_7\Models\QuotationGoodsModel;
use App\V3\V3_2_7\Models\AdminModel;
use App\V3\V3_2_7\Models\QuotationTagModel;
use App\V3\V3_2_7\Models\AdminAddendumModel;
use OSS\OssClient;

class QuotationNoController extends BaseController
{
    protected $ossClient;
    public function __construct(Request $request){
        parent::__construct($request);
        $this->ossClient=new OssClient(
            config('app.aliyun_oss_key'),
            config('app.aliyun_oss_secret'),
            config('app.aliyun_oss_endpoint')
            );
    }
    /**
     * 添加报价单
     */
    public function add(Request $request){

        $admininfo   = AdminAddendumModel::select('is_vip','empty_bill_amount')
            ->where(['main_id'=>$this->getMainUserId()])->first()->toArray();

        if(!empty($admininfo) && in_array($admininfo['is_vip'],[1,2])){

           /*  $total_amount = DispatchListService::countReceiptsTotal(['main_id'=>$this->getMainUserId()]);

            if($admininfo['empty_bill_amount'] != -1 && $total_amount >= $admininfo['empty_bill_amount']){

                return $this->fail('','您创建的报价单，已达到设置数量！');
            } */

        }else{

            return $this->fail('','您还不是VIP会员，还不能创建空白单据！');
        }
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'total_cost'        =>'numeric|min:0',//本单合计
            'down_payment'      =>'numeric|min:0',//预付定金
            'preferential_price'=>'numeric|min:0',//优惠价
            'balance_payment'   =>'numeric|min:0',//尾款

        ],[
            'total_cost.numeric'        => '本单合计只能为数字',
            'total_cost.min'            => '本单合计最小只能为0',
            'down_payment.numeric'      => '预付定金只能为数字',
            'down_payment.min'          => '预付定金最小只能为0',
            'preferential_price.numeric'=> '优惠价只能为数字',
            'preferential_price.min'    => '优惠价最小只能为0',
            'balance_payment.numeric'   => '尾款只能为数字',
            'balance_payment.min'       => '尾款最小只能为0',

        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
/*        $data['tag_list']='[{"tag_name":"掌上网络01","goods_list":[{"name":"苹果","type_name":"红","product_unit":"件","price":"5.6","num":"10","remark":"好吃的很","serial_number":11,"goods_img":"214124.png"},{"name":"水梨","type_name":"黄","product_unit":"件","price":"3.6","num":"8","remark":"好吃的很","serial_number":22,"goods_img":"56757.png"}]},{"tag_name":"掌上网络02","goods_list":[{"name":"苹果","type_name":"红","product_unit":"件","price":"5.6","num":"10","remark":"好吃的很","serial_number":11,"goods_img":"214124.png"},{"name":"水梨","type_name":"黄","product_unit":"件","price":"3.6","num":"8","remark":"好吃的很","serial_number":22,"goods_img":"56757.png"}]}]';
 */       //开启事务
       DB::beginTransaction();
        try{
            //报价单
            $dData = $data;
               if(empty($dData['offer_company'])){

                   $uInfo = AdminModel::select('company_name')->where('id', $this->getMainUserId())->first();

                   if(!empty($uInfo['company_name'])){//主账号信息里的公司名称填写为报价单公司

                       $dData['offer_company']=$uInfo['company_name'];
                   }
               }
            $dData['created_at']    = time();
            $dData['user_id']       = $this->getUserId();
            $dData['main_id']       = $this->getMainUserId();

            if(empty($dData['quotation_no'])){

             $dData['quotation_no']  = $this->getMainUserId().TimeUtil::getMillisecond();//报价单号
            }else{

                $condition['quotation_no'] = $dData['quotation_no'];
                $condition['user_id']  = $this->getUserId();
                $condition['main_id']  = $this->getMainUserId();

                $info = QuotationNoService::getQuotationNoInfo($condition);

                if(!empty($info)){

                    return $this->fail('','报价单编号,已存在！');
                }
            }
            unset($dData['tag_list']);
            $quotation_id           = QuotationNoService::add($dData);

            if(!empty(isset($data['tag_list']) && !empty($data['tag_list']))){

                $goodsData = json_decode($data['tag_list'],true);

                foreach ($goodsData as $gk=>$gv){
                    $tData['created_at']=time();
                    $tData['quotation_id']=$quotation_id;
                    $tData['tag_name']=$gv['tag_name'];
                    $tData['user_id']       = $this->getUserId();
                    $tData['main_id']       = $this->getMainUserId();
                    $tag_id = QuotationTagModel::insertGetId($tData);

                    //商品详细添加
                    if(isset($gv['goods_list']) && !empty($gv['goods_list'])){

                        foreach ($gv['goods_list'] as $value){

                            $value['created_at']  = time();
                            $value['tag_id']      = $tag_id;
                            $value['quotation_id']= $quotation_id;
                            $value['user_id']     = $this->getUserId();
                            $value['main_id']     = $this->getMainUserId();
                            QuotationGoodsModel::insert($value);
                        }
                    }

                }

            }
            DB::commit();//提交事务
            $this->log("添加报价单", $dData, '单号：'.$dData['quotation_no'].'创建成功！');
            return $this->success();
        }catch (\Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'添加报价单');
        }

    }

    /**
     * 删除报价单信息
     * @param ids (删除多个逗号分隔)
     */
    public function delete(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'ids'       =>'required',//报价单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }
        $id_data = [];
        $id_arr  = explode(',',$data['ids']);
        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();

        $list = QuotationNoModel::select('id','quotation_no')
                ->where($condition)->whereIn('id',$id_arr)->get()->toArray();
        $orderNo = "";
        if(!empty($list)){

            foreach ($list as $k=>$v){
                $id_data[]=$v['id'];
                $orderNo .= $v['quotation_no'].'、';
            }
            DB::beginTransaction();
            try {

                    $bool = QuotationNoModel::where($condition)->whereIn('id',$id_data)->delete();

                    if($bool){
                        $gList = QuotationGoodsModel::select('goods_img')->where($condition)->whereIn('quotation_id',$id_data)->get();
                        QuotationTagModel::where($condition)->whereIn('quotation_id',$id_data)->delete();
                        $bool = QuotationGoodsModel::where($condition)->whereIn('quotation_id',$id_data)->delete();
                        if($bool){
                            foreach ($gList as $gv){
                                if(!empty($gv['goods_img'])){

                                    $delOssRes = self::delOssFilePath($gv['goods_img'], $this->ossClient, $this->getMainUserId());
                                    if(!empty($delOssRes)) return $this->fail('',$delOssRes);
                                }
                            }
                        }
                    }else{
                        return $this->fail('','删除失败');
                    }
                    DB::commit();
                    $this->log("删除报价单", $id_data, '单号：'.$orderNo.'已删除！');
                    return $this->success();
                } catch (\Exception $e) {
                    DB::rollBack();
                    return $this->fail('',$e->getMessage());
                }
            }
            return $this->fail('','报价单，不存在！');


    }

    /**
     * 删除商品
     * @param Request $request
     */
    public function delGoods(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'goods_ids'         => 'required',//商品id
            'quotation_id'      => 'required',//报价单id
        ],[
            'goods_ids.required' => '商品主键id`缺失`',
            'quotation_id.required' => '报价单主键id`缺失`'
            ]);

        $id_arr  = explode(',',$data['goods_ids']);

        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();
        $condition['quotation_id'] = $data['quotation_id'];
        $gList = QuotationGoodsModel::select('goods_img')->where($condition)->whereIn('id',$id_arr)->get();
        DB::beginTransaction();
        try {
            $bool  = QuotationGoodsModel::where($condition)->whereIn('id',$id_arr)->delete();
            if($bool){
                foreach ($gList as $gv){
                    if(!empty($gv['goods_img'])){

                        $delOssRes = self::delOssFilePath($gv['goods_img'], $this->ossClient, $this->getMainUserId());
                        if(!empty($delOssRes)) return $this->fail('',$delOssRes);
                    }
                }
            }
            DB::commit();
            $this->log("删除报价单商品", $id_arr);
            return $this->success();
         } catch (\Exception $e) {
            DB::rollBack();
            return $this->fail('',$e->getMessage());
        }
    }

    /**
     * 删除标签
     * @param Request $request
     */
    public function delTags(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'tag_ids'         => 'required',//商品id
            'quotation_id'      => 'required',//报价单id
        ],[
            'quotation_id.required' => '报价单主键id`缺失`',
            'tag_ids.required'=>'标签主键id`缺失`'
        ]);

        $id_arr  = explode(',',$data['tag_ids']);

        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();
        $condition['quotation_id'] = $data['quotation_id'];
        $gList = QuotationGoodsModel::select('goods_img')->where($condition)->whereIn('tag_id',$id_arr)->get();
      DB::beginTransaction();
      try {
            QuotationTagModel::where($condition)->whereIn('id',$id_arr)->delete();
            $bool = QuotationGoodsModel::where($condition)->whereIn('tag_id',$id_arr)->delete();
            if($bool){
                foreach ($gList as $gv){
                    if(!empty($gv['goods_img'])){

                        $delOssRes = self::delOssFilePath($gv['goods_img'], $this->ossClient, $this->getMainUserId());
                        if(!empty($delOssRes)) return $this->fail('',$delOssRes);
                    }
                }
            }
            DB::commit();
            $this->log("删除报价单商品标签", $id_arr);
            return $this->success();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->fail('',$e->getMessage());
        }
    }
    /**
     * 修改报价单
     *
     */
    public function update(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'quotation_id'      =>'required|integer',//报价单id
            'total_cost'        =>'numeric|min:0',//本单合计
            'down_payment'      =>'numeric|min:0',//预付定金
            'preferential_price'=>'numeric|min:0',//优惠价
            'balance_payment'   =>'numeric|min:0',//尾款

        ],[
            'quotation_id.required'   => '报价单主键id缺失',
            'quotation_id.integer'   => '报价单主键id为正整数',
            'total_cost.numeric'        => '本单合计只能为数字',
            'total_cost.min'            => '本单合计最小只能为0',
            'down_payment.numeric'      => '预付定金只能为数字',
            'down_payment.min'          => '预付定金最小只能为0',
            'preferential_price.numeric'=> '优惠价只能为数字',
            'preferential_price.min'    => '优惠价最小只能为0',
            'balance_payment.numeric'   => '尾款只能为数字',
            'balance_payment.min'       => '尾款最小只能为0',

        ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
     /*    $data['tag_list']='[{"tag_id":1,"tag_name":"掌上网络0999","goods_list":[{"goods_id":1,"name":"苹果99997777","type_name":"红","product_unit":"件","price":"5.6","num":"10","remark":"好吃的很","serial_number":11,"goods_img":"214124.png"},{"name":"水梨","type_name":"黄","product_unit":"件","price":"3.6","num":"8","remark":"好吃的很","serial_number":22,"goods_img":"56757.png"}]},{"tag_id":2,"tag_name":"掌上网络09999","goods_list":[{"goods_id":2,"name":"苹果99997777","type_name":"红","product_unit":"件","price":"5.6","num":"10","remark":"好吃的很","serial_number":11,"goods_img":"214124.png"},{"name":"水梨","type_name":"黄","product_unit":"件","price":"3.6","num":"8","remark":"好吃的很","serial_number":22,"goods_img":"56757.png"}]},{"tag_name":"掌上网络09999","goods_list":[{"name":"苹果99997777","type_name":"红","product_unit":"件","price":"5.6","num":"10","remark":"好吃的很","serial_number":11,"goods_img":"214124.png"},{"name":"水梨","type_name":"黄","product_unit":"件","price":"3.6","num":"8","remark":"好吃的很","serial_number":22,"goods_img":"56757.png"}]}]'; */
        $info = QuotationNoService::getQuotationNoInfo(['id'=> $data['quotation_id']]);

        if(empty($info)){

            return $this->fail('','报价单号,不存在！');
        }
        //开启事务
        DB::beginTransaction();
        try{
            //报价单
            $updData = $data;

            $condition['user_id'] = $this->getUserId();
            $condition['main_id'] = $this->getMainUserId();
            $condition['id']      = $updData['quotation_id'];
          if(!empty(isset($data['tag_list']) && !empty($data['tag_list']))){

            $goodsData = json_decode($data['tag_list'],true);

            foreach ($goodsData as $gk=>$gv){

                $tData['tag_name'] = $gv['tag_name'];
                $tData['quotation_id']  = $updData['quotation_id'];
                $tData['main_id']       = $this->getMainUserId();
                if(isset($gv['tag_id'])){

                    $tag_id = $gv['tag_id'];
                    $tData['updated_at'] = time();

                    QuotationTagModel::where(['id'=>$gv['tag_id']])->update($tData);

                }else{
                    $tData['created_at']=time();
                    $tag_id = QuotationTagModel::insertGetId($tData);
                }
                //商品详细添加
                if(isset($gv['goods_list']) && !empty($gv['goods_list'])){

                    foreach ($gv['goods_list'] as $value){

                        $value['tag_id'] = $tag_id;
                        //更新
                        if(isset($value['goods_id'])){
                            $dCondition['id'] = $value['goods_id'];
                            unset($value['goods_id']);
                            if(!empty($value['goods_img'])){
                                $gInfo = QuotationGoodsModel::select('goods_img')->where($dCondition)->first();
                                if($value['goods_img']!=$gInfo['goods_img']){
                                    $delOssRes = self::delOssFilePath($gInfo['goods_img'], $this->ossClient, $this->getMainUserId());
                                    if(!empty($delOssRes)) return $this->fail('',$delOssRes);
                                }
                            }
                            QuotationGoodsModel::where($dCondition)->update($value);
                        }else{//添加

                            $value['created_at']  = time();
                            $value['user_id']     = $this->getUserId();
                            $value['main_id']     = $this->getMainUserId();
                            $value['quotation_id'] = $updData['quotation_id'];

                            QuotationGoodsModel::insert($value);
                        }
                    }

                }

            }
        }
            unset($updData['tag_list']);
            unset($updData['quotation_id']);
            $updData['updated_at'] = time();
            $quotation_id = QuotationNoService::update($condition,$updData);
            DB::commit();//提交事务
            $this->log("修改报价单", $updData, '单号：'.$info['quotation_no'].'，信息已更改！');
            return $this->success();
        }catch (\Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'修改报价单');
        }

    }

    /**
     * 报价单信息
     * @param quotation_id
     */
    public function find(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'quotation_id'       =>'required|integer',//报价单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }


        $condition['id'] = $data['quotation_id'];
        $list['tag_list'] = [];
       $info = QuotationNoModel::where($condition)->first()->toArray();
        if(!empty($info)){

                $tag_list = QuotationTagModel::select("id","tag_name")->where(['quotation_id'=>$info['id']])->get()->toArray();

                if(!empty($tag_list)){

                    foreach ($tag_list as $k=>$v){
                        $list['tag_list'][$k]['id']=$v["id"];
                        $list['tag_list'][$k]['name']=$v["tag_name"];
                        $list['tag_list'][$k]['goods_list']=QuotationGoodsModel::where(['tag_id'=>$v['id']])->get()->toArray();
                    }
                }
                $list = array_merge($info,$list);
                $this->log("报价单信息", $list);
            return $this->success($list);
        }else{
            $this->fail('','此报价单，没有找到！');
        }

    }

    /**
     * 报价单列表
     */
    public function QuotationNoList(Request $request){

        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'page_size' =>'required|integer',//页面大小
            'current_page' =>'required|integer',//当前页
        ], [
            'page_size.required' => '参数`页面大小`丢失',
            'page_size.integer' => '参数`页面大小`仅能为数字',
            'current_page.required' => '参数`当前页码`丢失',
            'current_page.integer' => '参数`当前页码`仅能为数字',
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $id_arr01 = [];
        $id_arr02 = [];
        $quotation_id_arr = [];

        $keyword = empty($data['keyword'])?'':$data['keyword'];
    if($this->getMainUserId() != 0){
        if($this->getUserId() == $this->getMainUserId()) {
                $condition['main_id'] = $this->getMainUserId();
            }
            else {
                if($this->isShareBillhead()) {

                    $condition['main_id'] = $this->getMainUserId();
                }else {
                    $condition['main_id'] = $this->getMainUserId();
                    $condition['user_id'] = $this->getUserId();
                }
            }
        }else{
            $condition['user_id'] = $this->getUserId();
        }
        if(!empty($keyword)){

            $goodsList = QuotationGoodsModel::select('quotation_id')
            ->where($condition)
            ->where(function($query) use ($keyword) {
                $query->orWhere('name', 'like', '%'.$keyword.'%');
                $query->orWhere('type_name', 'like', '%'.$keyword.'%');
                $query->orWhere('serial_number', 'like', '%'.$keyword.'%');
            })
            ->orderBy('quotation_id','DESC')
            ->get()->toArray();

            if(!empty($goodsList)){

                foreach ($goodsList as $k=>$v){

                    $id_arr01[$k] = $v['quotation_id'];
                }
            }

            $list = QuotationNoModel::select('id')->where($condition)
            ->where(function($query) use ($keyword) {
                $query->orWhere('quotation_no', 'like', '%'.$keyword.'%');
                $query->orWhere('customer_name', 'like', '%'.$keyword.'%');
                $query->orWhere('customer_phone', 'like', '%'.$keyword.'%');
                $query->orWhere('customer_address', 'like', '%'.$keyword.'%');
            })->orderBy('id','desc')
            ->get()->toArray();

            if(!empty($list)){

                foreach ($list as $k=>$v){

                    $id_arr02[$k] = $v['id'];
                }
            }

            $quotation_id_arr = array_unique(array_merge($id_arr01,$id_arr02));

            if(empty($quotation_id_arr)){

                $quotation_id_arr[0] ="0";
            }
        }

        $list = QuotationNoService::getList($condition,$quotation_id_arr,$data['page_size'],$data['current_page']);

        if(!empty($list['data'])){

            foreach ($list['data'] as $key=>$value){

                $tag_list = QuotationTagModel::select('id','tag_name')->where('quotation_id',$value['id'])->get()->toArray();

                $list['data'][$key]['tag_list']=$tag_list;

                foreach ($tag_list as $tk=>$tv){

                    $query = QuotationGoodsModel::where('quotation_id',$value['id'])->where(['tag_id'=>$tv['id']]);

                    if(!empty($id_arr01)){

                        $query->where(function($query) use ($keyword) {
                            $query->orWhere('name', 'like', '%'.$keyword.'%');
                            $query->orWhere('type_name', 'like', '%'.$keyword.'%');
                            $query->orWhere('serial_number', 'like', '%'.$keyword.'%');
                        });
                    }

                    $list['data'][$key]['tag_list'][$tk]['goods_list'] =  $query->get();
                }
            }
        }
        $this->log("报价单列表", $list);
        return $this->success($list);

    }

   static public  function get_between($input, $start, $end) {

        $substr = substr($input, strlen($start)+strpos($input, $start),(strlen($input) - strpos($input, $end))*(-1));

        return $substr;

    }

    /**
     * 上传商品图片（单个）
     * @param goods_img 商品图片
     */
    public function uploadGoodsImg(Request $request){

        if(!empty($goods_img_file = $request->file('goods_img'))){

            $res = self::handlePicFormat($goods_img_file, '商品图片格式，不正确！');

            if(!empty($res)) return response()->json($res);

            if($goods_img_file->isValid()){
                $imgPath  = $goods_img_file->store('baojiadao/goods/img/'.date('Y').'-'.date('m').'-'.date('d'));
                 $imgRes  = self::addOssUploadImg($this->getMainUserId(),$this->ossClient, $goods_img_file, $imgPath);
                if($imgRes['code'] === 0){

                    $path = $imgRes['data'];
                    return ['code' => 0, 'msg' => 'success', 'data' => ['path'=>$path]];
                }else{
                    return response()->json($imgRes);
                }

            }else{

                return response()->json(['code'=>1,'msg'=>'上传失败','data'=>'']);
            }

        }else{
                return response()->json(['code'=>1,'msg'=>'请选择商品图片','data'=>'']);

        }

    }


    /**
     * 图片上传到oss系统
     * @param unknown $client
     * @param unknown $file
     */
    static public function addOssUploadImg($mainId,$client,$file,$path){
        $res = handleUploadFileType($file);
        if(!empty($res)) return $res;
        $size = $file -> getSize();
         $result = saveFileSize(['main_id'=>$mainId], $size,$path);
        if($result['code'] == 1) return $result;
        try {

            $fullPath = '/uploads/'.$path;
            $ossPath  = ltrim($fullPath,'./');
            $path     = public_path().$fullPath;
            $client -> uploadFile(config('app.aliyun_oss_bucket'), $ossPath, $path);
            @unlink($path);
            $url = config('app.aliyun_oss_bucket_url').$fullPath;
            return ["code"=>0,"msg"=>"success","data"=>$url];

        } catch (\Exception $e) {

            return ["code"=>1,"msg"=>"OSS系统，上传图片失败！","data"=>""];
        }
    }

    /**
     * 删除oss里的文件
     * @param unknown $file
     * @param unknown $mainId
     */
    static public function delOssFilePath($file,$client,$mainId){
        if(empty($file)) return $file;
            DB::beginTransaction();
            try {
                $delPath = strstr($file, 'uploads/');
                $imgInfo=$client->getObjectMeta(config('app.aliyun_oss_bucket'), $delPath);
                AdminAddendumModel::where(['main_id'=>$mainId])
                ->decrement('file_total_size', $imgInfo['content-length']);
                $client -> deleteObject(config('app.aliyun_oss_bucket'), $delPath);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return "";
            }
    }

    /**
     * 处理图片格式
     */
    static public function handlePicFormat($files,$msg){

        $pic_format = 'bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,wmf,webp,avif,apng';


        $ext = $files->extension();

        $ext = strtolower($ext);

       $pic_format = explode(',',$pic_format);

        if (!in_array($ext, $pic_format)) {

            return ['code' => 1,'msg' => $msg,'data' => ''];die;
        }

    }

}
